package com.hw8.mongo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

@Component
public class MongoUtils {

    private static MongoTemplate mongoTemplate;
    @Autowired
    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        MongoUtils.mongoTemplate = mongoTemplate;
    }

    /**
     * 保存对象
     */
    public static String saveObj(Object object) {
        mongoTemplate.save(object);
        return "添加成功";
    }

    /***
     * 根据id查询
     * @param id
     * @return
     */
    public static <T> T getById(String id,Class<T> entityClass) {
        Query query = new Query(Criteria.where("_id").is(id));
        return mongoTemplate.findOne(query, entityClass);
    }

    /**
     * 根据名称查询
     * @param name
     * @return
     */
    public static <T> T getByName(String name,Class<T> entityClass) {
        Query query = new Query(Criteria.where("name").is(name));
        return mongoTemplate.findOne(query, entityClass);
    }

    /**
     * 获取下一段自增ID
     *
     * @param collectionName 集合名称,要同步的ID是用在哪里的
     * @return 最后的id值
     */
    public static Long getNextId(String collectionName) {
        Query query = new Query(Criteria.where("collectionName").is(collectionName));
        Update update = new Update();
        update.inc("nextId", 1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        // 先查询，如果没有符合条件的，会执行插入，插入的值是查询值 ＋ 更新值
        options.upsert(true);
        // 返回当前最新值
        options.returnNew(true);
        Counters seq = mongoTemplate.findAndModify(query, update, options, Counters.class);
        if(seq != null){
            return seq.getNextId();
        }
        return 0l;
    }

    public static int getNextId(Class clazz) {
        return getNextId(clazz.getSimpleName()).intValue();
    }

}
